package dao.impl;

import dao.UserDao;
import entity.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.DataSourceUtils;

import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {

    private QueryRunner qr = new QueryRunner(DataSourceUtils.getDs());

    @Override
    public User findByUsernameAndPassword(String username, String password) {

        try {
            User user = qr.query("select * from user where username=? and password=?", new BeanHandler<>(User.class), username, password);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public List<User> findAll() {
        try {
            List<User> users = qr.query("select * from user", new BeanListHandler<>(User.class));

            return users;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User findById(int id) {
        try {
            User user = qr.query("select * from user where id=?", new BeanHandler<>(User.class), id);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public void updateById(User user) {
        String sql = "UPDATE USER SET NAME=?,gender=?,age=?,address=?,qq=?,email=?,bir=? WHERE id=?";
        Object[] params = {user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),user.getBir(),user.getId()};
        try {
            qr.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteById(int id) {
        try {
            qr.update("delete from user where id=?",id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insert(User user) {
        String sql = "insert into user (name,gender,age,address,qq,email,bir) values (?,?,?,?,?,?,?)";
        Object[] params = {user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),user.getBir()};

        try {
            qr.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
